package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.TiXianBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/3/20 0020.
 */

public class TiXianActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.tv_name)
    TextView tv_name;
    @Bind(R.id.tv_zh)
    TextView tvZh;
    @Bind(R.id.modify_zfb)
    TextView modifyZfb;
    @Bind(R.id.phone)
    TextView phone;
    @Bind(R.id.ed_code)
    EditText edCode;
    @Bind(R.id.tvcode)
    TextView tvcode;
    @Bind(R.id.et_money)
    EditText etMoney;
    @Bind(R.id.submit)
    TextView submit;
    public SharedPreferences sp;
    public SharedPreferences.Editor editor;
    @Bind(R.id.money)
    TextView money;
    private String telcode;
    private int type = 0;
    private String seceret;
    private String cookie;
    private int typeId;

    @Override
    public int bindLayout() {
        return R.layout.activity_tixian;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        title.setText("提现");
        back.setOnClickListener(this);
        modifyZfb.setOnClickListener(this);
        tvcode.setOnClickListener(this);
        submit.setOnClickListener(this);
        edCode.addTextChangedListener(textWatcher);
        etMoney.addTextChangedListener(textWatcher);
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable edt) {
                String temp = edt.toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) {
                    return;
                }
                if (temp.length() - posDot - 1 > 2) {
                    edt.delete(posDot + 3, posDot + 4);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
        });
    }

    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            SimpleDateFormat formatter = new SimpleDateFormat("dd");
            Date curDate = new Date(System.currentTimeMillis());
            //获取当前时间
            String str = formatter.format(curDate);
            if (!TextUtils.isEmpty(tv_name.getText()) && !TextUtils.isEmpty(tvZh.getText()) && !TextUtils.isEmpty(phone.getText()) && !TextUtils.isEmpty(edCode.getText()) && !TextUtils.isEmpty(etMoney.getText()) && Integer.parseInt(str) > 24) {
                submit.setBackgroundResource(R.drawable.edittext_red_style);
                submit.setEnabled(true);
            } else {
                submit.setBackgroundResource(R.drawable.edittext_style_dark);
                submit.setEnabled(false);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        telcode = sp.getString("code", "");
        phone.setText(sp.getString("userPhone", ""));
        getSessionId();

    }

    public void GetUserInfo() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetUserInfo(cookie, sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TiXianBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(TiXianBean bean) {
                if (bean.getCode().equals("0")) {
                    tv_name.setText(bean.getData().getUserName());
                    tvZh.setText(bean.getData().getUserAlipay());
                    money.setText(bean.getData().getAvailableMoeny());
                }
            }
        });
    }

    public void GetTeamMoenyInfo() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetTeamMoenyInfo(cookie, sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TiXianBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(TiXianBean bean) {
                if (bean.getCode().equals("0")) {
                    tv_name.setText(bean.getData().getUserName());
                    tvZh.setText(bean.getData().getUserAlipay());
                    money.setText(bean.getData().getAvailableMoeny());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.modify_zfb: {
                startActivity(new Intent(this, BindZhifuBaoActivity.class));
            }
            break;
            case R.id.tvcode: {
                if (RegexValidateUtils.checkCellphone(phone.getText().toString())) {
                    typeId = 1;
                } else {
                    typeId = 2;
                }
                getCode();
            }
            break;
            case R.id.submit: {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (type == 0) {
                    GetMoney();
                } else {
                    getMoney2();
                }
            }
            break;
            default:
                break;
        }
    }

    public void getCode() {
        timer.start();
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetCode(phone.getText().toString().trim(), typeId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "phone" + phone.getText().toString().trim()+"typeId"+typeId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(TiXianActivity.this).showMessage("发送异常");
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    ToastUtils.getInstance(TiXianActivity.this).showMessage(json.getString("message"));
                    telcode = json.getString("data");
                    editor.putString("code", telcode);
                    editor.apply();
                } else if (json.get("code").equals("-1")) {
                    ToastUtils.getInstance(TiXianActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }

    /**
     * 取消倒计时
     *
     * @param v
     */
    public void oncancel(View v) {
        timer.cancel();
    }

    /**
     * 开始倒计时
     *
     * @param v
     */
    public void restart(View v) {
        timer.start();
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvcode.setEnabled(false);
            tvcode.setTextColor(Color.GRAY);
            tvcode.setText((millisUntilFinished / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            tvcode.setEnabled(true);
            tvcode.setTextColor(getResources().getColor(R.color.theme_color));
            tvcode.setText("发送验证码");
            timer.cancel();
        }
    };

    public void GetMoney() {
        String phone = sp.getString("userPhone", "");
        String txian = etMoney.getText().toString().trim();
        if (TextUtils.isEmpty(edCode.getText()) || TextUtils.isEmpty(etMoney.getText())) {
            return;
        }
        if (!edCode.getText().toString().trim().equals(telcode)) {
            ToastUtils.getInstance(this).showMessage("验证码错误");
            return;
        }
        if (Double.parseDouble(etMoney.getText().toString()) > Double.parseDouble(money.getText().toString())) {
            ToastUtils.getInstance(this).showMessage("提现金额不能大于可提现金额");
            return;
        }
        if (Double.parseDouble(txian) == 0) {
            ToastUtils.getInstance(this).showMessage("提现金额不能为0");
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).SetPresentData(cookie, phone, txian, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + phone + "UserMoeny" + txian)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    ToastUtils.getInstance(TiXianActivity.this).showMessage(obj.getString("message"));
                    GetUserInfo();
                } else {
                    ToastUtils.getInstance(TiXianActivity.this).showMessage(obj.getString("message"));
                }
            }
        });
    }

    public void getMoney2() {
        String phone = sp.getString("userPhone", "");
        String txian = etMoney.getText().toString().trim();
        if (TextUtils.isEmpty(edCode.getText()) || TextUtils.isEmpty(etMoney.getText())) {
            return;
        }
        if (!edCode.getText().toString().trim().equals(telcode)) {
            ToastUtils.getInstance(TiXianActivity.this).showMessage("验证码错误");
            return;
        }
        if (Double.parseDouble(etMoney.getText().toString()) > Double.parseDouble(money.getText().toString())) {
            ToastUtils.getInstance(TiXianActivity.this).showMessage("提现金额不能大于可提现金额");
            return;
        }
        if (Double.parseDouble(txian) == 0) {
            ToastUtils.getInstance(TiXianActivity.this).showMessage("提现金额不能为0");
            return;
        }
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).SetCashWithdrawals(cookie, phone, txian, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + phone + "UserMoeny" + txian)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    ToastUtils.getInstance(TiXianActivity.this).showMessage(obj.getString("message"));
                    GetTeamMoenyInfo();
                } else {
                    ToastUtils.getInstance(TiXianActivity.this).showMessage(obj.getString("message"));
                }
            }
        });
    }

    public void getSessionId() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetSessionId(RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    seceret = json.getString("data");
                    cookie = json.getString("message");
                    Bundle bundle = getIntent().getExtras();
                    if (null != bundle) {
                        type = bundle.getInt("type");
                    }
                    if (type == 0) {
                        GetUserInfo();
                    } else {
                        GetTeamMoenyInfo();
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }
}
